import { PlayerEntity } from '../entity/PlayerEntity';
import { PlayerAchievementValue } from '../value/PlayerAchievementValue';
import { PlayerService } from '../service/PlayerService';

// 玩家聚合 - 作为一个完整的业务单元
export class PlayerAggregate {
  private playerService: PlayerService = new PlayerService();
  
  constructor(
    public playerEntity: PlayerEntity,
    public achievements: PlayerAchievementValue[] = []
  ) {}
  
  // 玩家完成案件
  public completeCase(
    caseId: string,
    correct: boolean,
    caseDifficulty: number,
    timeTaken: number,
    isFirstAttempt: boolean
  ): void {
    // 更新玩家信息
    if (correct) {
      this.playerEntity.solvedCases++;
      
      // 计算并添加经验值
      const expReward = this.playerService.calculateCaseRewardExp(
        this.playerEntity,
        caseDifficulty,
        timeTaken,
        isFirstAttempt
      );
      this.playerEntity.addExperience(expReward);
    }
    
    // 更新准确率
    this.playerService.updateAccuracy(this.playerEntity, correct);
    
    // 检查新成就
    const newAchievements = this.playerService.checkForNewAchievements(
      this.playerEntity,
      this.achievements
    );
    
    // 添加新成就
    newAchievements.forEach(achievement => {
      this.achievements.push(achievement);
    });
  }
  
  // 更新玩家偏好设置
  public updatePreferences(preferences: Partial<PlayerEntity['preferences']>): void {
    this.playerEntity.preferences = {
      ...this.playerEntity.preferences,
      ...preferences
    };
  }
  
  // 开始新案件
  public startNewCase(caseId: string): void {
    this.playerEntity.currentCaseId = caseId;
  }
  
  // 获取玩家统计信息
  public getStatistics(): PlayerStatistics {
    return {
      level: this.playerEntity.level,
      experience: this.playerEntity.experience,
      solvedCases: this.playerEntity.solvedCases,
      accuracy: this.playerEntity.accuracy,
      totalAchievements: this.achievements.length,
      achievementPoints: this.achievements.reduce((sum, a) => sum + a.points, 0),
      levelProgress: this.playerService.getLevelProgressPercentage(this.playerEntity)
    };
  }
}

// 玩家统计信息接口
export interface PlayerStatistics {
  level: string;
  experience: number;
  solvedCases: number;
  accuracy: number;
  totalAchievements: number;
  achievementPoints: number;
  levelProgress: number;
}
